package njci.softerware.com.myexpress2017.chart;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.phillipcalvin.iconbutton.IconButton;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import njci.softerware.com.myexpress2017.R;
import njci.softerware.com.myexpress2017.activity.PackageTableDetail;
import njci.softerware.com.myexpress2017.http.HttpClient;
import njci.softerware.com.myexpress2017.http.HttpResponseHandler;
import njci.softerware.com.myexpress2017.serviceObj.PackageDispatcher;
import njci.softerware.com.myexpress2017.serviceObj.PackageRecevie;
import njci.softerware.com.myexpress2017.serviceObj.PackageSign;
import njci.softerware.com.myexpress2017.serviceObj.dao.PackageDispatcherDao;
import njci.softerware.com.myexpress2017.serviceObj.dao.PackageRecevieDao;
import njci.softerware.com.myexpress2017.serviceObj.dao.PackageSignDao;
import njci.softerware.com.myexpress2017.serviceObj.dao.SharedPreferences;
import njci.softerware.com.myexpress2017.utils.Constant;
import njci.softerware.com.myexpress2017.utils.WeekToDay;
import okhttp3.FormBody;
import okhttp3.Request;

public class PieChartActivity extends DemoBase implements
        OnChartValueSelectedListener, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.mapqueryBtn)
    IconButton mapqueryBtn;
    private String mapQueryText;
    private String mapTitle;
    private PieChart mChart;
    private float countSign;
    private float countDispa;
    private float countRece;
    private Integer postDelayWeek = 0;
    ArrayList<PieEntry> entries;
    List<PackageDispatcher> ds;
    SharedPreferences sh = SharedPreferences.getInstance();
    List<PackageRecevie> rs;
    List<PackageSign> sn;
    Integer peopleId;
    private SwipeRefreshLayout mSwipeLayout;
    Button searchMonthButton;
    Button searchDayButton;
    Button searchWeekButton;
    String actionName = "findPackageAndUserByweek";
    String date;
    int mothNum = 0;
    List<String> weekList;
    int searchType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_piechart);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        ButterKnife.bind(this);
        searchType = getIntent().getExtras().getInt(Constant.searchType);
        sh = SharedPreferences.getInstance();
        peopleId = sh.getInt("userId", 0);
        switch (searchType) {
            case Constant.search_day:
                actionName = "findPackageAndUserById";
                date = WeekToDay.getKnowDay();
                mapQueryText = "上一天";
                mapTitle = "当天";
                break;
            case Constant.search_week:
                actionName = "findPackageAndUserByweek";
                weekList = WeekToDay.getWeekbeginAndEnd(postDelayWeek);
                mapQueryText = "上一周";
                mapTitle = "本周" + weekList.get(0) + " | " + weekList.get(6);
                break;
            case Constant.search_moonth:
                actionName = "findPackageAndUserByMoth";
                date = WeekToDay.getMothCompareKnow(mothNum) + "%";
                mapQueryText = "上一月";
                mapTitle = "本月 | " + date;
                break;
            default:
                break;
        }
        mapqueryBtn.setText(mapQueryText);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                initDate(actionName);
            }
        }, 3000);
        mChart = (PieChart)
                findViewById(R.id.chart1);
        initFreSh();
        setData();

        mChart.setUsePercentValues(true);
        //mChart.getDescription().setEnabled(false);
        mChart.setExtraOffsets(5, 10, 5, 5);


        mChart.setDragDecelerationFrictionCoef(0.95f);

        mChart.setCenterTextTypeface(mTfLight);
        mChart.setCenterText(

                generateCenterSpannableText()

        );

        mChart.setDrawHoleEnabled(true);
        mChart.setHoleColor(Color.WHITE);

        mChart.setTransparentCircleColor(Color.WHITE);
        mChart.setTransparentCircleAlpha(110);

        mChart.setHoleRadius(58f);
        mChart.setTransparentCircleRadius(61f);

        mChart.setDrawCenterText(true);

        mChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        mChart.setRotationEnabled(true);
        mChart.setHighlightPerTapEnabled(true);
        mChart.setOnChartValueSelectedListener(this);
    }


    private void initDate(String actionName) {
        recevieData("0", "1", "10", actionName, date);
        recevieData("1", "1", "10", actionName, date);
        recevieData("2", "1", "10", actionName, date);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.pie, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.actionToggleValues: {
                for (IDataSet<?> set : mChart.getData().getDataSets())
                    set.setDrawValues(!set.isDrawValuesEnabled());
                mChart.invalidate();
                break;
            }
            case R.id.actionToggleHole: {
                if (mChart.isDrawHoleEnabled())
                    mChart.setDrawHoleEnabled(false);
                else
                    mChart.setDrawHoleEnabled(true);
                mChart.invalidate();
                break;
            }
            case R.id.actionDrawCenter: {
                if (mChart.isDrawCenterTextEnabled())
                    mChart.setDrawCenterText(false);
                else
                    mChart.setDrawCenterText(true);
                mChart.invalidate();
                break;
            }
            case R.id.actionToggleXVals: {
                mChart.setDrawEntryLabels(!mChart.isDrawEntryLabelsEnabled());
                mChart.invalidate();
                break;
            }
            case R.id.actionSave: {
                // mChart.saveToGallery("title"+System.currentTimeMillis());
                mChart.saveToPath("title" + System.currentTimeMillis(), "");
                break;
            }
            case R.id.actionTogglePercent:
                mChart.setUsePercentValues(!mChart.isUsePercentValuesEnabled());
                mChart.invalidate();
                break;
            case R.id.animateX: {
                mChart.animateX(1400);
                break;
            }
            case R.id.animateY: {
                mChart.animateY(1400);
                break;
            }
            case R.id.animateXY: {
                mChart.animateXY(1400, 1400);
                break;
            }
            case R.id.actionToggleSpin: {
                mChart.spin(1000, mChart.getRotationAngle(), mChart.getRotationAngle() + 360, Easing.EasingOption
                        .EaseInCubic);
                break;
            }
        }
        return true;
    }


    private void setData() {
        entries = new ArrayList<PieEntry>();
        countRece = findDbRSize(peopleId);
        countDispa = findDbDSize(peopleId);
        countSign = findDbSSize(peopleId);
        String recevieComment = "揽收 | " + countRece + "件";

        String disComment = "派送 | " + countDispa + "件";

        String signComment = "签收 | " + countSign + "件";

        if (countRece == 0.0) {
            countRece = 0.000001f;
            recevieComment = "无揽收";
        }

        if (countDispa == 0.0) {
            disComment = "无派送";
            countDispa = 0.000001f;
        }

        if (countSign == 0.0) {
            signComment = "无签收";
            countSign = 0.000001f;
        }


        entries.add(new PieEntry((countRece), recevieComment));
        entries.add(new PieEntry((countSign), signComment));
        entries.add(new PieEntry((countDispa), disComment));

        PieDataSet dataSet = new PieDataSet(entries, mapTitle + "详情");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        try {
            dataSet.setColors(colors);
            //dataSet.setSelectionShift(0f);

            PieData data = new PieData(dataSet);
            data.setValueFormatter(new PercentFormatter());
            data.setValueTextSize(11f);
            data.setValueTextColor(Color.WHITE);
            data.setValueTypeface(mTfLight);
            mChart.setData(data);

            // undo all highlights
            mChart.highlightValues(null);

            mChart.invalidate();
            mChart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String s = v.getId() + "";
                    Toast.makeText(PieChartActivity.this, s, Toast.LENGTH_LONG).show();
                }
            });

            mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
            // mChart.spin(2000, 0, 360);


            Legend l = mChart.getLegend();
            l.setPosition(LegendPosition.RIGHT_OF_CHART);
            l.setXEntrySpace(7f);
            l.setYEntrySpace(0f);
            l.setYOffset(0f);

            // entry label styling
            mChart.setEntryLabelColor(Color.WHITE);
            mChart.setEntryLabelTypeface(mTfRegular);
            mChart.setEntryLabelTextSize(12f);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("MPAndroidChart" + "\n" + "developed by Philipp Jahoda");
        s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

        if (e == null)
            return;

        String sTmp = h.getX() + "";
        Intent intent = new Intent(PieChartActivity.this, PackageTableDetail.class);
        int activityType = -1;
        makeText(sTmp);
        switch (sTmp) {
            //本周
            case "0.0":
                activityType = 0;
                break;
            //本月
            case "1.0":
                activityType = 2;
                break;
            //当天
            case "2.0":
                activityType = 1;
                break;
            default:
                break;
        }
        if (postDelayWeek != 0) {
            intent.putExtra("weekList", postDelayWeek);
        } else if (date != null && date.length() > 0) {
            intent.putExtra("dateType", date);
        }

        intent.putExtra("activityType", activityType);
        startActivity(intent);
    }

    @Override
    public void onNothingSelected() {
        Log.i("PieChart", "nothing selected");
    }


    public void makeText(String content) {
        Toast.makeText(PieChartActivity.this, content, Toast.LENGTH_LONG).show();
    }

    public synchronized void recevieData(final String postType, String beginPage, String pageSize, String actionName, String date) {

        // findPackageAndUserByweek;
        String url = "http://myexpress2016.carp.mopaasapp.com/";
        url = url + actionName;
        SharedPreferences sh = SharedPreferences.getInstance();
        Integer peopleId = sh.getInt("userId", 0);
        String userId = peopleId.toString();
        FormBody.Builder builder = new FormBody.Builder();
        FormBody formBody = null;
        if (date != null && date.length() > 0) {
            builder.add("date", date);
        }
        formBody = builder.add("userId", userId).add("postType", postType).add("beginPage", beginPage).add("pageSize", pageSize)
                .build();
        try {
            HttpClient.post(url, formBody, new HttpResponseHandler() {
                @Override
                public void onSuccess(String content) {
                    int num = 0;
                    if (content != null && !content.contains("error")) {
                        Log.d(Constant.TAG, "onSuccess:" + content);
                        Gson g = new Gson();

                        switch (postType) {
                            case "0":
                                rs = new ArrayList<PackageRecevie>();
                                Type type = new TypeToken<ArrayList<PackageRecevie>>() {
                                }.getType();
                                rs = g.fromJson(content, type);
                                if (rs != null && rs.size() > 0) {
                                    saveDbR(rs);
                                    num = rs.size();

                                }
                                SharedPreferences sh = SharedPreferences.getInstance();
                                if (num > 0) {
                                    sh.putInt("recevie_count", num);
                                } else {
                                    sh.putInt("recevie_count", -1);
                                }

                                if (sh.getInt("dis_count", 0) != 0 && sh.getInt("sign_count", 0) != 0) {
                                    setData();
                                }

                                break;
                            case "1":
                                ds = new ArrayList<PackageDispatcher>();
                                Type type1 = new TypeToken<ArrayList<PackageDispatcher>>() {
                                }.getType();
                                ds = g.fromJson(content, type1);

                                if (ds != null && ds.size() > 0) {
                                    saveDbD(ds);
                                    num = ds.size();
                                }
                                SharedPreferences sh1 = SharedPreferences.getInstance();
                                if (num > 0) {
                                    sh1.putInt("dis_count", num);
                                } else {
                                    sh1.putInt("dis_count", -1);
                                }

                                if (sh1.getInt("recevie_count", 0) != 0 && sh1.getInt("sign_count", 0) != 0) {
                                    setData();
                                }

                                break;
                            case "2":
                                sn = new ArrayList<PackageSign>();
                                Type type2 = new TypeToken<ArrayList<PackageSign>>() {
                                }.getType();
                                sn = g.fromJson(content, type2);
                                if (sn != null && sn.size() > 0) {
                                    saveDbS(sn);
                                    num = sn.size();
                                }

                                SharedPreferences sh2 = SharedPreferences.getInstance();
                                if (num > 0) {
                                    sh2.putInt("sign_count", num);
                                } else {
                                    sh2.putInt("sign_count", -1);
                                }

                                if (sh2.getInt("recevie_count", 0) != 0 && sh2.getInt("dis_count", 0) != 0) {
                                    setData();
                                }

                            default:
                                break;
                        }

                    } else {
                        Log.d(Constant.TAG, "login error:" + content);
                        Toast.makeText(PieChartActivity.this, "获取数据失败", Toast.LENGTH_LONG).show();
                    }

                }

                @Override
                public void onFailure(Request request, IOException e) {
                    Log.d(Constant.TAG, "onFailure:" + e.getMessage());
                    Toast.makeText(PieChartActivity.this, "链接服务器失败", Toast.LENGTH_LONG).show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(Constant.TAG, e.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void saveDbD(List<PackageDispatcher> list) {
        PackageDispatcherDao packageDispatcherDao = new PackageDispatcherDao(getApplicationContext());
        packageDispatcherDao.addList(list);
    }

    public Integer findDbDSize(Integer userId) {
        PackageDispatcherDao packageDispatcherDao = new PackageDispatcherDao(getApplicationContext());
        Integer size = packageDispatcherDao.getListCount(userId, date, weekList);
        return size;
    }

    public void saveDbR(List<PackageRecevie> list) {
        PackageRecevieDao packageRecevieDao = new PackageRecevieDao(getApplicationContext());
        packageRecevieDao.addList(list);
    }

    public Integer findDbRSize(Integer userId) {
        PackageRecevieDao packageRecevieDao = new PackageRecevieDao(getApplicationContext());
        Integer size = packageRecevieDao.getListCount(userId, date, weekList);
        return size;
    }


    public void saveDbS(List<PackageSign> list) {
        PackageSignDao packageSignDao = new PackageSignDao(getApplicationContext());
        packageSignDao.addList(list);
    }

    public Integer findDbSSize(Integer userId) {
        PackageSignDao packageSignDao = new PackageSignDao(getApplicationContext());
        Integer size = packageSignDao.getListCount(userId, date, weekList);
        return size;
    }

    public void initFreSh() {
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        mSwipeLayout.setOnRefreshListener(this);
        // 设置下拉圆圈上的颜色，蓝色、绿色、橙色、红色
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        mSwipeLayout.setDistanceToTriggerSync(400);// 设置手指在屏幕下拉多少距离会触发下拉刷新
        mSwipeLayout.setSize(SwipeRefreshLayout.LARGE);
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                initDate(actionName);
                mSwipeLayout.setRefreshing(false);
            }
        }, 5000); // 5秒后发送消息，停止刷新
    }

    @OnClick(R.id.mapqueryBtn)
    public void onClick() {
        switch (searchType) {
            case Constant.search_day:
                break;
            case Constant.search_week:
                postDelayWeek = postDelayWeek - 1;
                weekList = WeekToDay.getWeekbeginAndEnd(postDelayWeek);
                date = weekList.get(0);
                break;
            case Constant.search_moonth:
                mothNum = mothNum - 1;
                date = WeekToDay.getMothCompareKnow(mothNum) + "%";
                break;
            default:
                break;
        }
        initDate(actionName);
    }
}



